package servlet;

import java.awt.List;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.json.JSONArray;
import org.json.JSONObject;

import com.mongodb.client.MongoCursor;
import com.mongodb.util.JSON;

import mongo.UserAccount;
import mongo.Department;
import mongo.Major;
import mongo.Class;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(description = "profileProcess", urlPatterns = { "/common/profileServlet" })
public class profileServlet extends HttpServlet{
     
	private UserAccount UserAccount = new UserAccount();
	private Department Department = new Department();
	private Major Major = new Major();
	private Class Class = new Class();
	
    
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
	    
		String method = request.getParameter("method");
		if(method.equals("update")){
			this.update(request, response);
		}else if(method.equals("getmajor")){//获取当前系下的专业
			this.getmajor(request, response);
		}else if(method.equals("getclass")){//获取当前专业下的班级
			this.getclass(request, response);
		}else if(method.equals("changePwd")){
			this.changePwd(request, response);
		}else{
//			request.getRequestDispatcher("404.jsp").forward(request, response); 添加错误页面
		}
	
	}
	
	public void getmajor(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/text; charset=utf-8");
	    PrintWriter out = response.getWriter();
		ObjectId _id = new ObjectId(request.getParameter("_id"));
		ArrayList<Document> result = Major.listByDepartmentId(_id);
		JSONArray jsonArray = new JSONArray();
		for(int i=0;i<result.size();i++){
			jsonArray.put(JSON.parse(result.get(i).toJson()));
		}
		 try {
			 out.write(String.valueOf(jsonArray));
		} catch (Exception e) {
			 e.printStackTrace();
		}finally{
			out.close();
		}
	}
	
	public void getclass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/text; charset=utf-8");
	    PrintWriter out = response.getWriter();
		ObjectId _id = new ObjectId(request.getParameter("_id"));
		ArrayList<Document> result = Class.listByMajorId(_id);
		JSONArray jsonArray = new JSONArray();
		for(int i=0;i<result.size();i++){
			jsonArray.put(JSON.parse(result.get(i).toJson()));
		}
		 try {
			 out.write(String.valueOf(jsonArray));
		} catch (Exception e) {
			 e.printStackTrace();
		}finally{
			out.close();
		}
	}
	
	public void prepareUpdate(HttpServletRequest request, HttpServletResponse response)//学生用户更新的时候，选择的系、专业、班级的名称还有其id，非_id，要传过来
			throws ServletException, IOException {
		Boolean result = null;
		
        try {
        	MongoCursor<Document> departmentList = Department.list();
        	MongoCursor<Document> majorList = Major.list();
        	MongoCursor<Document> classList = Class.list();
        	//返回3个集合
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }	
	}
	

	public void update(HttpServletRequest request, HttpServletResponse response)//学生用户更新的时候，选择的系、专业、班级的名称还有其id，非_id，要传过来
			throws ServletException, IOException {
		Boolean result = null;
		
        try {
        	 //获取session对象
    	    HttpSession session = request.getSession();
        	ObjectId _id = new ObjectId(request.getParameter("_id"));
        	Document updateDocument = new Document();
        	Enumeration<String> names = request.getParameterNames();
        	while(names.hasMoreElements()){
        		String name = names.nextElement();
        		if(!name.equals("_id")&&!name.equals("login")) {
        			if(name.equals("departmentid")||name.equals("majorid")||name.equals("classid")) {
            			ObjectId id = new ObjectId(request.getParameter(name));
            			updateDocument.append(name, id);
            		}
        			else {
        				String value = request.getParameter(name);
                		updateDocument.append(name, value);
        			}    			
        		}
        	}
    		result= UserAccount.update(_id, updateDocument);
        	Document newUserInfo = UserAccount.getUserInfo(_id);
        	session.setAttribute("result", newUserInfo);
        	if(request.getParameter("type").equals("t")) {
        		response.sendRedirect("../teacher/teacherInfo.jsp");
        	}
        	else {
        		response.sendRedirect("../student/studentInfo.jsp");
        	}
        	//TODO更新session的用户信息
    		//TODO针对返回结果和所属模块，返回到相对应的页面
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }	
	}
	
	public void changePwd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	HttpSession session = request.getSession();
        	ObjectId _id = new ObjectId(request.getParameter("_id"));
        	String newPwd = request.getParameter("newPwd");
        	Boolean result = UserAccount.changePwd(_id,newPwd);
        	Document newUserInfo = UserAccount.getUserInfo(_id);
        	session.setAttribute("result", newUserInfo);
        	response.sendRedirect("../login.jsp");
        	//TODO更新session的用户信息
        	//TODO修改成功或失败跳转
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }
	}
	
}
